local lspconfig = require("lspconfig")
local mason_lspconfig = require("mason-lspconfig")
local capabilities = require("cmp_nvim_lsp").default_capabilities()
local M = {}

-- 通用 on_attach 配置
M.on_attach = function(client, bufnr)
  -- 禁用格式化功能 (推荐使用专门的格式化工具如 null-ls)
  client.server_capabilities.documentFormattingProvider = false
  client.server_capabilities.documentRangeFormattingProvider = false

  -- 通用键位映射
  local opts = { buffer = bufnr, noremap = true, silent = true }
  vim.keymap.set("n", "gd", vim.lsp.buf.definition, opts)
  vim.keymap.set("n", "K", vim.lsp.buf.hover, opts)
  vim.keymap.set("n", "<leader>rn", vim.lsp.buf.rename, opts)
end

-- 配置各语言服务器 (新版兼容方式)
mason_lspconfig.setup_handlers({
  -- 默认处理程序
  function(server_name)
    lspconfig[server_name].setup({
      on_attach = on_attach,
      capabilities = capabilities
    })
  end,
  
  -- Python 特殊配置
  pyright = function()
    lspconfig.pyright.setup({
      on_attach = on_attach,
      capabilities = capabilities,
      settings = {
        python = {
          analysis = {
            typeCheckingMode = "basic"
          }
        }
      }
    })
  end,
  
  -- Clangd 特殊配置
  clangd = function()
    lspconfig.clangd.setup({
      on_attach = on_attach,
      capabilities = capabilities,
      cmd = {
        "/usr/bin/clangd",
        "--background-index",
        "--clang-tidy",
        "--header-insertion=iwyu"
      }
    })
  end
})

M.capabilities = capabilities
M.lspconfig = lspconfig
M.mason_lspconfig = mason_lspconfig

-- 确保 Mason 已初始化
require("mason").setup()
mason_lspconfig.setup({
  ensure_installed = { "pyright" },
  --ensure_installed = { "pyright", "clangd"},
  handlers = {
        clangd = function() end -- 完全跳过 clangd 处理
  }
})

return M
